package cn.shadow.module.login;

import cn.shadow.bean.PlayerModule;
import cn.shadow.module.chess.message.ChessModule;
import cn.shadow.module.chess.message.ChessModuleMessages;
import cn.shadow.moulde.*;
import cn.shadow.proto.client.PlayerBasicClientProtoContent;
import cn.shadow.proto.client.PlayerClientProtoContent.*;
import cn.shadow.utils.BufferUtil;
import io.netty.buffer.ByteBuf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Scanner;

/**
 * Created time:2020-02-10 23:28:06
 */
@Service
@AModule(Modules.LOGIN_MODULE_ID)
public class LoginModule extends Module {
    @Autowired
    private Scanner scanner;


    @AHandler(LoginModuleMessages.S2C_LOGIN_RESULT)
    public void request(ByteBuf buffer, PlayerModule module) {
        int result = BufferUtil.readVarInt32(buffer);
        if (result == 1) {
            System.out.println("您已经登录成功,但是未有角色现在为您创角,请输入您的昵称：");
            requestCreatePlayer(module);
        } else if (result == 2) {
            System.out.println("您已经登录成功!");
        }
    }

    /**
     * 请求创建角色
     */
    private void requestCreatePlayer(PlayerModule module) {
        String nickName = scanner.nextLine();
        ByteBuf playerBuffer = LoginModuleMessages.createPlayerBuffer(nickName);
        module.sendMessage(playerBuffer);
    }

    @AHandler(LoginModuleMessages.S2C_CREATE__PLAYER)
    public void createPlayer(ByteBuf buffer, PlayerModule module) throws Exception {
        boolean result = BufferUtil.readBoolean(buffer);
        if (result) {
            byte[] bytes = BufferUtil.readBytes(buffer);
            PlayerClientProto proto = PlayerClientProto.parseFrom(bytes);
            PlayerBasicClientProtoContent.PlayerBasicClientProto basic = proto.getBasic();
            System.out.println("角色信息如下:");
            System.out.println("Id:" + basic.getId());
            System.out.println("昵称:" + basic.getName());
            System.out.println("性别:" + (basic.getIsMale() ? "男" : "女"));
            doInvite(basic.getId(),module);
        } else {
            String code = BufferUtil.readUTF(buffer);
            System.out.println("创建角色失败");
            System.out.println("失败原因:" + code);
            System.out.println("未有角色现在为您创角,请输入您的昵称：");
            requestCreatePlayer(module);
        }
    }

    private void doInvite(long id, PlayerModule module) {
        long playerId= 3518441503850506L;
        ByteBuf invitePlayerMsg = ChessModuleMessages.InvitePlayerMsg(id, playerId, 1);
        module.sendMessage(invitePlayerMsg);
    }

    @Autowired
    ChessModule chessModule;

}
